package com.ucode.admin.cgms.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ucode.cgms.service.CgmsGiftRewardOrderService;
import com.ucode.cgms.service.CgmsGiftService;
import com.ucode.member.service.MemberService;
import com.ucode.model.cgms.CgmsGift;
import com.ucode.model.cgms.CgmsGiftRewardOrder;
import com.ucode.model.cgms.convert.CgmsGiftRewardOrderConvert;
import com.ucode.model.cgms.vo.CgmsGiftRewardOrderVO;
import com.ucode.model.member.Member;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResponseResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.*;

@Tag(name = "管理后台 - 陪玩社区系统 - 礼物信息")
@RestController
@RequestMapping("/cgms/gift-reward-order")
@Validated
public class CgmsGiftRewardOrderController {

    @Resource
    private MemberService memberService;
    @Resource
    private CgmsGiftService cgmsGiftService;

    @Resource
    private CgmsGiftRewardOrderService cgmsGiftRewardOrderService;

    @GetMapping("/page-list")
    @Operation(summary = "获得分页列表")
    @PreAuthorize("@usfs.hasPermission('cgms:gift-reward-order:query')")
    public ResponseResult<Paginator<CgmsGiftRewardOrderVO>> pageList(
            @Schema(description = "礼物编号") @RequestParam(value = "giftId",required = false) String giftId,
            @Schema(description = "打赏类型",allowableValues = {"1","2"}) @RequestParam(value = "rewardType",required = false) Integer rewardType,
            @Schema(description = "状态,参见CommonSwitchStatusEnum枚举类",allowableValues = {"0","1"}) @RequestParam(value = "status",required = false) Integer status,
            @Schema(description = "创建时间区间",example = "[2022-07-01 00:00:00,2022-07-01 23:59:59]")  @RequestParam(value = "createTimeInterval",required = false) LocalDateTime[] createTimeInterval,
            @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){

        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(giftId)) {
            condition.put("giftId", giftId);
        }
        condition.put("rewardType",rewardType);
        if(ArrayUtil.isNotEmpty(createTimeInterval) && createTimeInterval.length == 2){
            condition.put("startTime",createTimeInterval[0]);
            condition.put("endTime",createTimeInterval[1]);
        }
        condition.put("payState",status);
        condition.put("deltag",false);

        return ResponseResult.success(pageList(condition,pageNum,pageSize));
    }

    @GetMapping("/getById/{id}")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH,example = "1024")
    @Operation(summary = "主键获得信息")
    @PreAuthorize("@usfs.hasPermission('cgms:gift-reward-order:query')")
    public ResponseResult<CgmsGiftRewardOrderVO> getById(@PathVariable(name="id",required=true) Long id){
        CgmsGiftRewardOrder bean = cgmsGiftRewardOrderService.selectByPrimaryKey(id);
        CgmsGiftRewardOrderVO beanVo = CgmsGiftRewardOrderConvert.INSTANCE.convert(bean);
        if (ObjUtil.isNotEmpty(beanVo.getGiftId())){
            CgmsGift gift = cgmsGiftService.selectByPrimaryKey(beanVo.getGiftId());
            beanVo.setGift(gift);
        }
        Member member = memberService.selectByPrimaryKey(beanVo.getCompanionUserId());
        if (ObjUtil.isNotEmpty(member)) {
            beanVo.setCompanionUserNickname(member.getNickname());
            beanVo.setCompanionUserAvatar(member.getAvatar());
        }
            Member rewardMember = memberService.selectByPrimaryKey(beanVo.getRewardUserId());
        if (ObjUtil.isNotEmpty(rewardMember)) {
            beanVo.setRewardUserNickname(rewardMember.getNickname());
            beanVo.setRewardUserAvatar(rewardMember.getAvatar());
        }
        return ResponseResult.success(beanVo);
    }

    @PostMapping("/logic-delete/{id}")
    @Operation(summary = "转移到回收站")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH, example = "1024")
    @PreAuthorize("@usfs.hasPermission('cgms:gift-reward-order:logic-delete')")
    public ResponseResult<Object> logicDelete(@PathVariable(name="id",required=true) Long id) {
        //逻辑删除
        int i = cgmsGiftRewardOrderService.logicDeletePrimaryKey(id);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

    @PostMapping("/batch-logic-delete")
    @Operation(summary = "批量转移到回收站")
    @PreAuthorize("@usfs.hasPermission('cgms:gift-reward-order:logic-delete')")
    public ResponseResult<Boolean> batchLogicDeletePrimaryKey(@Schema(description = "编号集合",requiredMode = Schema.RequiredMode.REQUIRED)
                                                @NotEmpty(message = "编号集合为空")@Size(min = 1,max = 20,message = "编号集合数量为1-20条")
                                                @RequestParam(value = "ids",required = true) List<Long> ids) {
        int i = cgmsGiftRewardOrderService.logicDeleteByPrimaryKeys(ids);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

    private Paginator<CgmsGiftRewardOrderVO> pageList(Map<String, Object> condition, Integer pageNum, Integer pageSize) {
        Paginator<CgmsGiftRewardOrder> paginator = cgmsGiftRewardOrderService.queryPageForList(condition, pageSize, pageNum);
        return this.pageList(paginator);
    }

    private Paginator<CgmsGiftRewardOrderVO> pageList(Paginator<CgmsGiftRewardOrder> paginator) {
        Paginator<CgmsGiftRewardOrderVO> paginatorVo = CgmsGiftRewardOrderConvert.INSTANCE.convertPage(paginator);
        List<CgmsGiftRewardOrderVO> list = paginatorVo.getList();
        Set<Long> memberIdsSet = new HashSet<>();
        Set<Long> giftIdsSet = new HashSet<>();
        if (CollUtil.isNotEmpty(list)) {
            for (CgmsGiftRewardOrderVO vo : list){
                memberIdsSet.add(vo.getCompanionUserId());
                memberIdsSet.add(vo.getRewardUserId());
                if (ObjectUtil.isNotEmpty(vo.getGiftId())) {
                    giftIdsSet.add(vo.getGiftId());
                }
            }
            Map<Long, Member>  memberMap =memberService.getMap(memberIdsSet);
            Map<Long, CgmsGift>  giftMap =cgmsGiftService.getMap(giftIdsSet);
            for(CgmsGiftRewardOrderVO vo : list) {
                Member memberInfo = memberMap.get(vo.getCompanionUserId());
                if (memberInfo != null) {
                    vo.setCompanionUserNickname(memberInfo.getNickname());
                    vo.setCompanionUserAvatar(memberInfo.getAvatar());
                }
                Member toMemberInfo = memberMap.get(vo.getRewardUserId());
                if (toMemberInfo != null) {
                    vo.setRewardUserNickname(toMemberInfo.getNickname());
                    vo.setRewardUserAvatar(toMemberInfo.getAvatar());
                }
                if (ObjectUtil.isNotEmpty(vo.getGiftId())){
                    CgmsGift giftInfo = giftMap.get(vo.getGiftId());
                    if (giftInfo != null) {
                        vo.setGift(giftInfo);
                    }
                }
            }

            paginatorVo.setList(list);
        }
        return paginatorVo;
    }
}
